#include "picoshell.h"
#include "user_lib.h"
#include "exit.h"
#define RETURN 13
#define BACKSPACE 8

int main()
{
	while(1) 
	{
		if (run() == -1)
			break;
	}
	exit();
}

int run()
{
	char input[100],login[40];
	char commande[20], argument[40], car; 
	int i=0,j=0,pos_espace=0, nb_espace=0, currentUID;
	
	for (i=0;i<40;i++)
		argument[i] = 0;			// efface l'argument précédent
	
	currentUID = syscall_user(SYSCALL_GETCURRENTUID);
	printString("\n");
	syscall_user(SYSCALL_GETLOGIN,currentUID,&login);
	
	printString(login);
	printString(" > ");
	getStringBackSpace(input);
/*
*	Decodage de la commande
*/
	i=0;
	while(input[i]!=0)					// vérifie la chaîne en la découpant en partie
	{
		if (input[i]==' ')
		{
			pos_espace=i;
			nb_espace++;
		}
		i++;
	}

	if(nb_espace>1) 
		printString("Too many arguments\n");	
	else if(nb_espace==1)
	{
		for(i=0;i<pos_espace;i++)		
			commande[i]=input[i];
		commande[i] = 0;				// terminaison de la chaine
		i=pos_espace+1;
		j=0;
		while(input[i]!=0)
			argument[j++]=input[i++];
	}
	else 	
		strcpy(commande,input);

/*
* Traitement de la commande
*/
	if (strcmp("ls", commande)) 
	{
		printString("\n");
		listFiles(); 
	}
	else if (strcmp("cat", commande)) {
		printString("\n");
		if (argument[0]) 
			printFile(argument) ;
		else 
			printString("\nError: no file name\n");
	}

	else if (strcmp("exec", commande)) {
		if (argument[0]) 
		{
			printString("\n");			
			exec(argument,0x3000) ;						// execute le programme au segment 0x3000
		}
		else 
			printString("\nError: no file name\n");
	}

	else if (strcmp("rm", commande)) {
		printString("\n");	
		if (argument[0]) 
			removeFile(argument) ;
		else 
			printString("\nError: no file name\n");
	}

	else if (strcmp("help", commande)) 
		displayHelp();

	else if (strcmp("logout", commande)) {
  		return -1;
	}
	else 
		printString("\nCommand not found (help)\n");	
		
}

void displayHelp(void)
{
	printString("\nEnter one of the following command: \n");
	printString("\n -- ls : listing of the files\n");
	printString("\n -- cat filename: printing of the given filename \n");
	printString("\n -- exec filename: execution of the given filename \n");
	printString("\n -- rm filename: delete the given filename \n");
	printString("\n -- logout : quit the session  \n");
}
